package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.secondActivity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.R;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.ActivityConsumer;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.ActivityDealer;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.ActivityProducer;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Product;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Trace;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceConnection.ProductServiceConnection;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl.ProductService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.ImageUtils;

public class ActivityAddGoodImg extends AppCompatActivity {

    private Button btnAddImg, btnBack;  // 添加图片按钮和返回按钮
    private ImageView iUser, iconAdd;   // 显示图片的 ImageView 和添加图标
    private FrameLayout imageFrame;     // 用于点击图片上传的布局

    private Product product;

    // 产品相关服务类
    private ProductServiceConnection productConnection;
    private SharedPreferences sharedPreferences;

    // 拍照相关变量
    private Uri photoUri; // 用于存储照片的 URI
    private ActivityResultLauncher<Uri> takePhotoLauncher; // 拍照的 ActivityResultLauncher
    private static final int REQUEST_CAMERA_PERMISSION = 100;
    private static final int REQUEST_STORAGE_PERMISSION = 101;

    @Override
    protected void onStart() {
        super.onStart();
        init();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (productConnection.isBound()) {
            unbindService(productConnection);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this); // 启用全屏显示
        setContentView(R.layout.activity_add_good_img);

        btnAddImg = findViewById(R.id.btn_add_img);
        btnBack = findViewById(R.id.btn_back);
        imageFrame = findViewById(R.id.image_frame);  // 用于触发点击选择图片

        iUser = findViewById(R.id.user_image);  // 显示用户图片
        iconAdd = findViewById(R.id.icon_add);  // 显示添加图标

        // 选择图片来源按钮
        imageFrame.setOnClickListener(v -> showImageSelectionMenu());

        // 提交图片按钮
        btnAddImg.setOnClickListener(v -> submitImg());

        // 返回主菜单按钮
        btnBack.setOnClickListener(v -> {
            finish();
        });


    }

    private void submitImg() {
        Trace trace = new Trace();
        Bitmap productImage = ImageUtils.drawable2bitmap(iUser.getDrawable());
        trace.setProductId(product.getProductId());
        trace.setDealerId(sharedPreferences.getInt("userId",-1));
        trace.setDealerImg(ImageUtils.bitmap2Blob(productImage));
        Boolean addProductInfo = productConnection.getService().addTraceabilityPicture(trace, sharedPreferences.getInt("role",-1));
        if (addProductInfo) {
            setResult(RESULT_OK);
            Intent intent = new Intent(this,ActivityDealer.class);
            startActivity(intent);
            finish();
        }
    }

    // 图片选择菜单监听
    private void showImageSelectionMenu() {
        String[] options = {"拍摄照片", "从图库选择"};
        new AlertDialog.Builder(this)
                .setTitle("选择图片来源")
                .setItems(options, (dialog, which) -> {
                    if (which == 0) {
                        takePhoto(); // 拍照
                    } else if (which == 1) {
                        openImagePicker(); // 从图库选择
                    }
                })
                .show();
    }

    // 拍照选择
    private void takePhoto() {
        // 确保在调用摄像头之前检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            // 创建临时文件的 URI
            File tempFile;
            try {
                // 创建用于存储照片的临时文件
                File storageDir = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                tempFile = File.createTempFile("photo_", ".jpg", storageDir);
                photoUri = FileProvider.getUriForFile(
                        this,
                        this.getPackageName() + ".fileprovider",
                        tempFile
                );
                takePhotoLauncher.launch(photoUri);
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "无法创建临时文件", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "请先授予相机权限", Toast.LENGTH_SHORT).show();
        }
    }

    // 从图库选择图片
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*"); // 只显示图片类型的文件
        startActivityForResult(intent, 1); // 请求码为 1
    }

    // 初始化
    private void init() {
        // 初始化拍照功能
        requestPermissions();
        initTakePhotoLauncher();
        sharedPreferences = getSharedPreferences("ACCOUNT_REMEMBER", MODE_PRIVATE);

        productConnection = new ProductServiceConnection(service -> {
            String info = getIntent().getStringExtra("productId");
            product = service.getProductInfoById(info);

        });
        Intent intent = new Intent(this, ProductService.class);
        bindService(intent, productConnection, BIND_AUTO_CREATE);
    }

    // 初始化摄像步骤0 获取权限
    private void requestPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
        }
    }

    // 初始化拍照步骤1
    private void initTakePhotoLauncher() {
        takePhotoLauncher = registerForActivityResult(
                new ActivityResultContracts.TakePicture(),
                success -> {
                    if (success && photoUri != null) {
                        showPhoto(); // 在成功拍照后显示照片
                    } else {
                        Toast.makeText(this, "拍照失败", Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    // 显示拍照后的图片
    private void showPhoto() {
        if (photoUri != null) {
            try {
                // 从 Uri 创建输入流并解码 Bitmap
                InputStream inputStream = this.getContentResolver().openInputStream(photoUri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                if (bitmap != null) {
                    iUser.setImageBitmap(bitmap);
                    iUser.setVisibility(View.VISIBLE); // 显示 ImageView
                    iconAdd.setVisibility(View.GONE); // 隐藏添加图标
                } else {
                    Toast.makeText(this, "无法解码图片", Toast.LENGTH_SHORT).show();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(this, "文件未找到", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == this.RESULT_OK && data != null) {
                Uri selectedImageUri = data.getData(); // 获取选中图片的 URI
                iUser.setImageURI(selectedImageUri);
                iUser.setVisibility(View.VISIBLE); // 显示 ImageView
                iconAdd.setVisibility(View.GONE); // 隐藏添加图标
            }
        }
    }
}

